<template>
  <div>
    <Card shadow>
        <iview-table
            ref="table"
            :baseURL="queryModel.baseURL"
            :menuId="dataModel.menuId"
            :columns="dataModel.columns"
            :order="dataModel.order"
            :pageNumber="pageModel.pageNumber"
            :pageSize="pageModel.pageSize"
            :defaultFilters="queryModel.defaultFilters"
            v-on="{changeSelect:changeSelect,changeTotalSize:changeTotalSize,events:events}">
        </iview-table>
        <br>
        <iview-page 
            :totalSize="pageModel.totalSize"
            :pageNumber="pageModel.pageNumber" 
            :pageSize="pageModel.pageSize"
            :pageSizeOpts="pageModel.pageSizeOpts"
            v-on="{changePageNumber:changePageNumber,changePageSize:changePageSize}">
        </iview-page>
    </Card>
    <Modal v-model="showModal" :closable='false' :mask-closable=true :width="500">
      <h3 slot="header" style="color:#2D8CF0">请选择相关负责人</h3>
      <Form ref="selectRow" :model="selectRow" :label-width="150">
        <Row>
          <Col span="18" offset="3">
            <FormItem label="请选择主管医生：">
              <Select v-model="selectRow.doctorId" clearable :label-in-value=true @on-change="changeDoctor">
                <Option v-for="item in doctors" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
            <FormItem label="请选择主管护士：">
              <Select v-model="selectRow.nurseId" clearable :label-in-value=true @on-change="changeNurse">
                <Option v-for="item in nurses" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
            <FormItem label="请选择主管客服：">
              <Select v-model="selectRow.customerId" clearable :label-in-value=true @on-change="changeCustomer">
                <Option v-for="item in customers" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="info" size="large" @click="doSetMain">设置</Button>
      </div>
    </Modal>
    <Modal v-model="loading">
      <h3 slot="header" style="color:#2D8CF0">正在打开病案,请稍后...</h3>
      <Progress :percent="this.$store.state.app.percent"></Progress>
      <div slot="footer">
      </div>
    </Modal>
    <Modal v-model="showEdit" @on-ok="save" ok-text="保存" :closable='false' :mask-closable=true :width="450">
      <h3 slot="header" style="color:#2D8CF0">患者信息</h3>
      <Row>
        <Col :span="22" offset="1">
          <Form ref="formItem" :model="formItem" :label-width="100">
            <FormItem label="患者姓名：" prop="categoryId">
              <Input v-model="formItem.name" size="large" placeholder="请填写内容..."/>
            </FormItem>
            <FormItem label="患者病历：">
              <Input v-model="formItem.medicalNumber" size="large" placeholder="请填写内容..."/>
            </FormItem>
            <FormItem label="患者性别：">
              <Select v-model="formItem.sex" size="large" style="width:100%">
                <Option value="1" key="1">男</Option>
                <Option value="2" key="2">女</Option>
              </Select>
            </FormItem>
            <FormItem label="患者生日：">
              <DatePicker v-model="formItem.birthday" size="large" type="date" placeholder="请选择出生日期" style="width: 100%"></DatePicker>
            </FormItem>
            <FormItem label="患者手机：">
              <Input v-model="formItem.phone" size="large" placeholder="请填写内容..."/>
            </FormItem>
          </Form>
        </Col>
      </Row>
    </Modal>
    <Modal v-model="showTemplate" @on-ok="save" :closable='false' :mask-closable=true :width="400">
      <h3 slot="header" style="color:#2D8CF0">请选择短信模板</h3>
      <Row>
        <Col span="20" offset="2">
          <Select v-model="templateId" filterable style="width: 100%">
            <Option v-for="item in templates" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="info" size="large" @click="doSend">发送</Button>
      </div>
    </Modal>
    <Modal v-model="showScore" @on-ok="evaluate" :closable='false' :mask-closable=true :width="500">
      <h3 slot="header" style="color:#2D8CF0">信用分调整</h3>
      <Row>
        <Col span="22" offset="1">
        <Form ref="scoreModel" :model="scoreModel" :label-width="100">
            <FormItem label="信用分条目：">
              <Select v-model="scoreModel.creditName" clearable :label-in-value=true @on-change="changeCredit">
                <Option v-for="item in credititems" :value="item.creditScore" :key="item.creditScore">{{ item.creditName }}</Option>
              </Select>
            </FormItem>
             <FormItem label="分值">
              <InputNumber v-model="scoreModel.score" :min="1" style="width: 100%"></InputNumber>
            </FormItem>
          </Form>
        </Col>
      </Row>
    </Modal>
  </div>
</template>

<script>
import iviewTable from '@/view/common/table/Table.vue';
import iviewPage from '@/view/common/page/Page.vue';
export default {
    components: {
        iviewTable,
        iviewPage
    },
    props: {
        menuId: {
            type: [Number, String],
            default: 400
        },
        checkDate: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            percent: '0',
            loading: false,
            showModal: false,
            showEdit: false,
            showTemplate: false,
            showScore: false,
            templateId: '',
            baseURL: '/user/patient',
            doctors: [],
            nurses: [],
            customers: [],
            credititems: [],
            templates: [],
            selectRows: [],
            selectRow: {},
            formItem: {},
            queryModel: {
                // 网关代理路径(必须)+资源路径(可选)
                baseURL: '/user/patient',
                defaultFilters: [
                ]
            },
            dataModel: {
                menuId: this.menuId,
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },{
                        title: '患者姓名',
                        key: 'name',
                        align: 'left',
                        sortable: true
                    },{
                        title: '病历号',
                        key: 'medicalNumber',
                        align: 'left',
                        sortable: true
                    },{
                        title: '患者昵称',
                        key: 'nickName',
                        align: 'left',
                        sortable: true
                    },{
                        title: '性别',
                        key: 'sex',
                        align: 'left',
                        sortable: true,
                        render: (h, params) => {
                            let temp = params.row.sex
                            if (temp === 1) {
                                temp = '男'
                            } else if (temp === 2) {
                                temp = '女'
                            }
                            return h('span', temp)
                        }
                    },{
                        title: '出生日期',
                        key: 'birthday',
                        align: 'left',
                        type: 'Date',
                        sortable: true
                    },{
                        title: '手机号码',
                        key: 'phone',
                        align: 'left',
                        sortable: true
                    },{
                        title: '主管医生',
                        key: 'doctorName',
                        align: 'left',
                        sortable: true
                    },{
                        title: '主管护士',
                        key: 'nurseName',
                        align: 'left',
                        sortable: true
                    },{
                        title: '主管客服',
                        key: 'customerName',
                        align: 'left',
                        sortable: true
                    },{
                        title: '信用分',
                        key: 'score',
                        align: 'left',
                        sortable: true
                    },{
                        title: '操作',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'default'
                                    },
                                    style: {
                                    },
                                    on: {
                                        click: () => {
                                            this.toMedical(params.row)
                                        }
                                    }
                                }, '查看病历')
                            ]);
                        }
                    }
                ],
                order: 'creation_time desc'
            },
            pageModel: {
                totalSize: 0,
                pageNumber: 1,
                pageSize: 10,
                pageSizeOpts: [10, 50, 100, 500]
            },
            scoreModel: {
                id: '',
                creditType: '',
                creditScore: '',
                creditName: ''
            }
        }
    },
    methods: {
        events (item) {
            if (item.path === 'add') {
                this.add()
            } else if (item.path === 'edit') {
                this.edit()
            } else if (item.path === 'delete') {
                this.delete()
            } else if (item.path === 'setMain') {
                this.setMain()
            } else if (item.path === 'send') {
                this.send()
            } else if (item.path === 'addScore') {
                this.addScore()
            } else if (item.path === 'subScore') {
                this.subScore()
            }
        },
        add () {
            this.$bus.toPath('/patient/details')
        },
        edit () {
            if (this.selectRows.length === 1) {
                this.$bus.init(this.formItem)
                this.formItem = this.selectRows[0]
                this.formItem.sex = this.formItem.sex + ''
                this.showEdit = true
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        save () {
            let url = this.baseURL + '/saveOrUpdate'
            this.$ajax.post(url, this.formItem).then((response) => {
                let {code, msg} = response.data
                if (code === 0) {
                    this.showEdit = false
                    this.$bus.alert('success', '保存成功', 3)
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        delete () {
            if (this.selectRows.length > 0) {
                this.$Modal.confirm({
                    title: '操作提示',
                    content: '<p>确认删除?</p>',
                    onOk: () => {
                        let ids = []
                        for (let row of this.selectRows) {
                            ids.push(row.id)
                        }
                        let url = this.baseURL + '/delete'
                        this.$ajax.post(url, ids).then((response) => {
                            let {code, msg} = response.data
                            if (code === 0) {
                                this.$bus.alert('success', msg)
                                this.refresh()
                            } else {
                                this.$bus.alert('error', msg)
                            }
                        })
                    }
                })
            } else {
                this.$bus.alert('warning', '请至少选择一条记录')
            }
        },
        loadDoctor () {
            let url = '/user/findByJob/1'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.doctors = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        loadNurse () {
            let url = '/user/findByJob/2'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.nurses = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        loadCustomer () {
            let url = '/user/findByJob/4'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.customers = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        changeDoctor (option) {
            this.selectRow.doctorId = option.value
            this.selectRow.doctorName = option.label
        },
        changeCredit (option) {
            this.scoreModel.score = option.value;
        },
        changeNurse (option) {
            this.selectRow.nurseId = option.value
            this.selectRow.nurseName = option.label
        },
        changeCustomer (option) {
            this.selectRow.customerId = option.value
            this.selectRow.customerName = option.label
        },
        setMain () {
            if (this.selectRows.length === 1) {
                this.loadDoctor()
                this.loadNurse()
                this.loadCustomer()
                this.selectRow = this.selectRows[0]
                this.showModal = true
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        doSetMain () {
            let url = this.baseURL + '/saveOrUpdate'
            this.$ajax.post(url, this.selectRow).then(r => {
                let {code, msg} = r.data
                if (code === 0) {
                    this.$bus.alert('success', '设置成功')
                    this.showModal = false
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        toMedical (row) {
            this.$store.state.app.percent = 0
            this.loading = true
            let timer = setInterval(() => {
                let percent = this.$store.state.app.percent
                if (percent < 100){
                    this.$store.state.app.percent = this.$store.state.app.percent + 20
                }
                if (percent >= 100) {
                    clearInterval(timer);
                    setTimeout(() => {
                        this.loading = false
                    },50)
                }
            },50)
            setTimeout(() => {
                let query = {
                    id: row.id
                }
                this.$store.state.app.patientId = row.id
                this.$bus.toPath('/medical', query)
            },100)
        },
        loadTemplate () {
            let url = '/user/sms/template/findAll'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.templates = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        send () {
            if (this.selectRows.length > 0) {
                this.loadTemplate()
                this.templateId = ''
                this.showTemplate = true
            } else {
                this.$bus.alert('warning', '请至少选择一条记录')
            }
        },
        doSend () {
            if (this.templateId !== '') {
                let ids = []
                for (let item of this.selectRows) {
                    ids.push(item.id)
                }
                let url = '/user/sms/send/' + this.templateId
                this.$ajax.post(url, ids).then(r => {
                    let {code, msg} = r.data
                    if (code === 0) {
                        this.$bus.alert('success', '发送成功')
                        this.showTemplate = false
                    } else {
                        this.$bus.alert('error', msg)
                    }
                })
            } else {
                this.$bus.alert('warning', '请选择一个模板')
            }
        },
        addScore () {
            this.$bus.init(this.scoreModel)
            let url = '/user/credititems/findCreditItems/1'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.credititems = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
            if (this.selectRows.length === 1) {
                this.scoreModel.type = 1
                this.selectRow = this.selectRows[0]
                this.showScore = true
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        subScore () {
            let url = '/user/credititems/findCreditItems/0'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.credititems = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
            this.$bus.init(this.scoreModel)
            if (this.selectRows.length === 1) {
                this.scoreModel.type = 2
                this.selectRow = this.selectRows[0]
                this.showScore = true
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        evaluate () {
            this.scoreModel.patientId = this.selectRow.id
            this.scoreModel.patientName = this.selectRow.name
            let url = '/user/score/saveOrUpdate'
            this.$ajax.post(url, this.scoreModel).then(r => {
                let {code, msg} = r.data
                if (code === 0) {
                    this.$bus.alert('success', '操作成功')
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        refresh () {
            if (this.checkDate) {
                this.queryModel.defaultFilters[0] = {'field': 'birthday', 'value1': this.$moment(new Date()).format('YYYY-MM-DD'), 'operate': '=='}
            }
            this.$refs.table.refresh()
        },
        changeSelect (selection) {
            this.selectRows = selection
        },
        changeTotalSize (totalSize) {
            this.pageModel.totalSize = totalSize
        },
        changePageNumber (pageNumber) {
            this.pageModel.pageNumber = pageNumber
        },
        changePageSize (pageSize) {
            this.pageModel.pageSize = pageSize
        },
        init () {
            this.refresh()
        }
    },
    mounted () {
        this.init()
    },
    watch: {
        '$route' (to) {
            if (to.path === '/patient/list') {
                this.init()
            }
        }
    }
}
</script>

<style>

</style>
